package smartcounters.androidclient;

import java.util.LinkedList;

import smartcounters.androidclient.WebServices.BillingWebServiceClient;
import smartcounters.androidclient.WebServices.InformationReaderWebServiceClient;
import smartcounters.androidclient.WebServices.OnResultReceiver;
import smartcounters.androidclient.model.AccountInfo;
import smartcounters.androidclient.model.Configuration;
import smartcounters.androidclient.model.UserInfo;
import smartcounters.androidclient.model.eOperationsEnum;
import smartcounters.androidclient.model.eUserPermissions;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.app.Activity;

public class MyUserInfoActivity extends Activity implements OnClickListener, OnResultReceiver {

	private String[] m_AccountsAssociatedWithArray;
	private int[] m_AccountIDsAssociatedWithArray;
	private AccountInfo[] m_AccountInfos;
	private double m_Usage;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_user_info_layout);
        
        m_Usage = 0;
        m_AccountsAssociatedWithArray = null;
        m_AccountIDsAssociatedWithArray = null;
        
        Button showInfo = (Button)findViewById(R.id.buttonShowInfo);
        showInfo.setOnClickListener(this);
        showInfo.setEnabled(false);
        
        InformationReaderWebServiceClient readerClient = new InformationReaderWebServiceClient(Configuration.getInstance().getServerAddress());
		readerClient.RegisterResultReceiver(this);
		readerClient.GetAllAccounts(Configuration.getInstance().getAdminAuthenticatedCredentials());
    }

    public void onClick(View arg0) {
    	if (arg0.getId() == R.id.buttonShowInfo) {
			Spinner accountIDSpinner = (Spinner)findViewById(R.id.myInfoAccountIDSpinner);
			int accountID = m_AccountIDsAssociatedWithArray[accountIDSpinner.getSelectedItemPosition()];
			
			BillingWebServiceClient billingClient = new BillingWebServiceClient(Configuration.getInstance().getServerAddress());
			billingClient.RegisterResultReceiver(this);
			billingClient.GetMonthlyUsageSoFar(Configuration.getInstance().getUserCredentials(), accountID);
		}
	}
    
    public void ReceiveResult(Message i_Msg) {
    	if (eOperationsEnum.values()[i_Msg.what] == eOperationsEnum.GetMonthlyUsageSoFar){
			if (i_Msg.obj == null) {
				EditText currentUsageEditText = (EditText)findViewById(R.id.myInfoUsageEditText);
				EditText sumToPayEditText = (EditText)findViewById(R.id.myInfoSumToPayEditText);
				
				currentUsageEditText.setText("");
				sumToPayEditText.setText("");
				
				TextView myInfoMessageTextView = (TextView)findViewById(R.id.myInfoMessageTextView);
				myInfoMessageTextView.setText("There are no usages for the requested account.");
			}
			else {
				String usageString = i_Msg.obj.toString();
				m_Usage = Double.parseDouble(usageString);
				EditText currentUsageEditText = (EditText)findViewById(R.id.myInfoUsageEditText);
				currentUsageEditText.setText(usageString + " Liters");
				
				BillingWebServiceClient billingClient = new BillingWebServiceClient(Configuration.getInstance().getServerAddress());
				billingClient.RegisterResultReceiver(this);
				billingClient.GetCurrentPrice(Configuration.getInstance().getAdminAuthenticatedCredentials());
			}
        }
    	else if (eOperationsEnum.values()[i_Msg.what] == eOperationsEnum.GetCurrentPrice){
    		double price = Double.parseDouble(i_Msg.obj.toString());
    		EditText sumToPayEditText = (EditText)findViewById(R.id.myInfoSumToPayEditText);
    		sumToPayEditText.setText(String.valueOf(m_Usage * price) + " NIS");
    	}
		else if (eOperationsEnum.values()[i_Msg.what] == eOperationsEnum.GetUserInformationByID){
			UserInfo userInfo = (UserInfo)i_Msg.obj;
			if (m_AccountsAssociatedWithArray == null){
				LinkedList<Integer> accountIDs = userInfo.getAccountsAssociatedWith();
				m_AccountsAssociatedWithArray = new String[accountIDs.size()];
				m_AccountIDsAssociatedWithArray = new int[accountIDs.size()];
				
				int i = 0;
				
				for (int accountID : accountIDs){
					AccountInfo account = findAccount(accountID);
					
					if (account != null){
						String text = account.getApartment() == -1 ? account.getCountry() + ", " + account.getCity() + ", " + account.getStreet() + ", " + String.valueOf(account.getHouse()) :
			        		account.getCountry() + ", " + account.getCity() + ", " + account.getStreet() + ", " + String.valueOf(account.getHouse()) + " / " + String.valueOf(account.getApartment());
						
						m_AccountsAssociatedWithArray[i] = text;
						m_AccountIDsAssociatedWithArray[i] = account.getAccountID();
					}
					
					i++;
				}
				
				Spinner accountIDSpinner = (Spinner)findViewById(R.id.myInfoAccountIDSpinner);
				
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, m_AccountsAssociatedWithArray);
				accountIDSpinner.setAdapter(adapter);
			}
			
			EditText myInfoUserNameEditBox = (EditText)findViewById(R.id.myInfoUserName);
			myInfoUserNameEditBox.setText(userInfo.getUsername());
			
			EditText myInfoPhoneEditBox = (EditText)findViewById(R.id.myInfoPhone);
			myInfoPhoneEditBox.setText(userInfo.getPhone());
			
			EditText myInfoMobilePhoneEditBox = (EditText)findViewById(R.id.myInfoMobilePhone);
			myInfoMobilePhoneEditBox.setText(userInfo.getMobilePhone());
			
			EditText myInfoEmailEditBox = (EditText)findViewById(R.id.myInfoEmail);
			myInfoEmailEditBox.setText(userInfo.getEmail());
			
			Button showBillButton = (Button)findViewById(R.id.buttonShowInfo);
	        showBillButton.setEnabled(true);
        }
		else if (eOperationsEnum.values()[i_Msg.what] == eOperationsEnum.GetAllAccounts){
			m_AccountInfos = (AccountInfo[])i_Msg.obj;
			
			if (Configuration.getInstance().getLoggedInUser().getUserPermissions().contains(eUserPermissions.All)){
	        	// If the user is an administrator, show him all the accounts.
	        	
				m_AccountsAssociatedWithArray = new String[m_AccountInfos.length];
				m_AccountIDsAssociatedWithArray = new int[m_AccountInfos.length];
				
				for (int i = 0; i < m_AccountInfos.length; i++){
					String text = m_AccountInfos[i].getApartment() == -1 ? m_AccountInfos[i].getCountry() + ", " + m_AccountInfos[i].getCity() + ", " + m_AccountInfos[i].getStreet() + ", " + String.valueOf(m_AccountInfos[i].getHouse()) :
						m_AccountInfos[i].getCountry() + ", " + m_AccountInfos[i].getCity() + ", " + m_AccountInfos[i].getStreet() + ", " + String.valueOf(m_AccountInfos[i].getHouse()) + " / " + String.valueOf(m_AccountInfos[i].getApartment());
					
					m_AccountsAssociatedWithArray[i] = text;
					m_AccountIDsAssociatedWithArray[i] = m_AccountInfos[i].getAccountID();
				}
				
				Spinner accountIDSpinner = (Spinner)findViewById(R.id.myInfoAccountIDSpinner);
				
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, m_AccountsAssociatedWithArray);
				accountIDSpinner.setAdapter(adapter);
				
				InformationReaderWebServiceClient readerClient = new InformationReaderWebServiceClient(Configuration.getInstance().getServerAddress());
	    		readerClient.RegisterResultReceiver(this);
	    		readerClient.GetUserInformationByID(Configuration.getInstance().getUserCredentials(), Configuration.getInstance().getUserCredentials().getID());
	        }
	        else{
	        	// If the user is a simple user, show him only accounts associated with him.
	        	
	        	InformationReaderWebServiceClient readerClient = new InformationReaderWebServiceClient(Configuration.getInstance().getServerAddress());
	    		readerClient.RegisterResultReceiver(this);
	    		readerClient.GetUserInformationByID(Configuration.getInstance().getUserCredentials(), Configuration.getInstance().getUserCredentials().getID());
	        }
        }
	}
    
    private AccountInfo findAccount(int i_AccountID){
		for (int i = 0; i < m_AccountInfos.length; i++){
			if (m_AccountInfos[i].getAccountID() == i_AccountID){
				return m_AccountInfos[i];
			}
		}
		
		return null;
	}
}
